package com.dragon.wangyiwork.utils;

import cn.hutool.core.io.file.FileNameUtil;
import com.dragon.wangyiwork.config.WorkConfig;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具类
 *
 * @author DragonGao
 */
public class FileUploadUtils
{

    private static final String RESOURCE_PREFIX = "/commodity/image/";

    private static String baseDir = WorkConfig.getProfile();



    /**
     * 根据文件路径上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(MultipartFile file) throws IOException
    {
        String suffix = FileNameUtil.getSuffix(file.getOriginalFilename());
        String fileName = UUID.randomUUID().toString() + "." + suffix;
        File desc = new File(baseDir + File.separator + fileName);
        if(!desc.exists()){
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        file.transferTo(desc);
        return RESOURCE_PREFIX+fileName;
    }









}
